<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="imgDataURL" alt="" class="preview" v-if="imgDataURL" />
      <img src="../../../assets/images/avatar.jpg" alt="" class="preview" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" accept="image/*" style="display: none" ref="iptRef" @change="onFileChange" />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="!imgDataURL" @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { updateAvatarAPI } from '@/api/user.js'
export default {
  name: 'UserAvatar',
  data() {
    return {
      imgDataURL: ''
    }
  },
  methods: {
    chooseImg() {
      // 模拟点击行为
      this.$refs.iptRef.click()
    },
    onFileChange(e) {
      console.dir(e.target.files)
      const files = e.target.files
      if (files.length === 0) {
      } else {
        // 1. 创建 FileReader 对象
        const fr = new FileReader()
        // 2. 调用 readAsDataURL 函数，读取文件内容
        fr.readAsDataURL(files[0])
        // 3. 监听 fr 的 onload 事件
        fr.onload = () => {
          this.imgDataURL = fr.result
        }
      }
    },
    // 上传用户头像
    async uploadAvatar() {
      const { data: res } = await updateAvatarAPI(this.imgDataURL)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$store.dispatch('user/initUser')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
